package 单周赛.history;

/**
 *
 */
public class 第325场单周赛 {

    public static void main(String[] args) {

        System.out.println(closetTarget(new String[]{"hello", "i", "am", "leetcode", "hello"},
                "hello", 1));

        // "acbbcccab"
        //2
        System.out.println(takeCharacters("abc", 1));

    }

    public static int closetTarget(String[] words, String target, int startIndex) {
        int count = -1;

        int n = words.length;
        for (int i = startIndex, j = 0; j < n; j++, i = (i + 1) % n) {
            if (words[i].equals(target)) {
                count = j;
                break;
            }
        }

        for (int i = startIndex, j = 0; j < n; j++, i = (i - 1 + n) % n) {
            if (words[i].equals(target)) {
                if (count == -1) {
                    count = j;
                } else {
                    count = Math.min(count, j);
                }
            }
        }

        return count;
    }

    /**
     * 双指针+滑动窗口
     * 先将 left指向s的0索引，right指向 len-1,从左往右统计a,b,c的数量，直到满足
     * a>=k,b>=k,c>=k的条件停止，此时统计的是[0,left-1]范围的
     * 字符，后面将 left--,将left-1位置的字符数量-1，然后将
     * right--,直至使得窗口内满足题目条件停止&&right>=left,全部过程中
     * 去满足条件的最少时间
     */
    public static int takeCharacters(String s, int k) {
        if (k == 0) return 0;
        int count = Integer.MAX_VALUE;
        int[] record = new int[3];
        int left = 0, right = s.length() - 1;
        while (left <= right && (record[0] < k || record[1] < k || record[2] < k)) {
            record[s.charAt(left) - 'a']++;
            left++;
        }
        if (record[0] >= k && record[1] >= k && record[2] >= k) {
            count = left;
        }

        while (left > 0) {
            left--;
            record[s.charAt(left) - 'a']--;

            while (right >= left && (record[0] < k || record[1] < k || record[2] < k)) {
                record[s.charAt(right) - 'a']++;
                right--;
            }

            if (record[0] >= k && record[1] >= k && record[2] >= k) {
                count = Math.min(count, left + s.length() - right - 1);
            }
        }

        return count == Integer.MAX_VALUE ? -1 : count;
    }

}
